package com.pai4j.netty.server.config;

import com.pai4j.netty.server.config.properties.RedisConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.time.Duration;


@Slf4j
public class RedisPool {

    private static JedisPool pool;

    /**
     * 初始化 jedis 连接池
     */
    public static void init(RedisConfig redisConfig) {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMinIdle(redisConfig.getMinIdle());
        poolConfig.setMaxWait(Duration.ofSeconds(redisConfig.getMaxWait()));
        pool = new JedisPool(poolConfig,
                             redisConfig.getHost(),
                             redisConfig.getPort(),
                             redisConfig.getTimeout(),
                             redisConfig.getPassword(),
                             redisConfig.getDatabase());
        log.info("Redis pool init success ...");
    }

    public static void destroy() {
        if (pool != null) {
            pool.close();
        }
    }

    /**
     * 获取连接资源
     *
     * @return
     */
    public static Jedis getJedisResource() {
        Assert.notNull(pool, "Redis pool is not initialized!");
        Jedis jedis = pool.getResource();
        Assert.notNull(jedis, "Redis pool is not used resource!");
        return jedis;
    }


}
